<template>
  <div class="chat-view">
    <van-nav-bar
      :title="userName"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    >
      <template #right>
        <van-icon name="ellipsis" size="20" @click="showActions = true" />
      </template>
    </van-nav-bar>

    <!-- 消息列表 -->
    <div class="message-list" ref="messageListRef">
      <div 
        v-for="(message, index) in messageList" 
        :key="index"
        :class="['message-item', message.isService ? 'message-service' : 'message-user']"
      >
        <div class="message-content">
          <div class="message-header">
            <span class="message-name">{{ message.isService ? '客服' : userName }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="message-bubble">
            {{ message.message }}
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <van-empty 
        v-if="messageList.length === 0"
        description="暂无消息，开始对话吧"
        image="chat-o"
        class="empty-state"
      />
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <van-field
        v-model="inputMessage"
        placeholder="请输入消息..."
        :border="false"
        autosize
        type="textarea"
        rows="1"
        maxlength="500"
        show-word-limit
        @keyup.enter="sendMessage"
      />
      <van-button 
        type="primary" 
        size="small"
        @click="sendMessage"
        :disabled="!inputMessage.trim() || !isConnected"
      >
        发送
      </van-button>
    </div>

    <!-- 操作菜单 -->
    <van-action-sheet
      v-model:show="showActions"
      :actions="actions"
      cancel-text="取消"
      @select="onActionSelect"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useWebSocketStore } from '../stores/websocket'
import { Toast } from 'vant'

const route = useRoute()
const router = useRouter()
const wsStore = useWebSocketStore()

const userId = ref(route.params.userId)
// 优先从 store 中获取用户名，其次从查询参数，最后使用默认值
const userName = computed(() => {
  const user = wsStore.userList.find(u => u.userId === userId.value)
  return user?.name || route.query.userName || '客户'
})
const serviceId = ref('1001')
const messageList = ref([])
const inputMessage = ref('')
const messageListRef = ref(null)
const showActions = ref(false)

// 使用 store 中的连接状态
const isConnected = computed(() => wsStore.isConnected)

// 操作菜单
const actions = [
  { name: '清空聊天记录', value: 'clear' }
]

// 消息处理器
const handleMessage = (messageData) => {
  // 只处理与当前用户相关的消息
  if (
    (messageData.from === userId.value && messageData.to === `service${serviceId.value}`) ||
    (messageData.from === `service${serviceId.value}` && messageData.to === userId.value)
  ) {
    messageList.value.push({
      message: messageData.message || messageData.content || '',
      timestamp: messageData.timestamp || new Date().toISOString(),
      isService: messageData.from === `service${serviceId.value}`
    })
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 初始化
const init = () => {
  // 确保 WebSocket 已连接
  if (!wsStore.isConnected) {
    wsStore.init()
  }
  
  // 注册消息处理器
  wsStore.registerMessageHandler(`chat_${userId.value}`, handleMessage)
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    return
  }

  if (!wsStore.isConnected) {
    Toast.fail({
      message: '未连接到服务器',
      duration: 2000
    })
    return
  }

  const success = wsStore.sendMessage(userId.value, inputMessage.value.trim())
  
  if (success) {
    // 添加到消息列表（乐观更新）
    messageList.value.push({
      message: inputMessage.value.trim(),
      timestamp: new Date().toISOString(),
      isService: true
    })
    
    inputMessage.value = ''
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } else {
    Toast.fail({
      message: '发送失败，请重试',
      duration: 2000
    })
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  // 如果是今天，显示时间
  if (diff < 86400000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 如果是昨天
  if (diff < 172800000) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 其他情况显示日期和时间
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 返回
const goBack = () => {
  router.back()
}

// 操作菜单选择
const onActionSelect = (action) => {
  if (action.value === 'clear') {
    messageList.value = []
    Toast('聊天记录已清空')
  }
  showActions.value = false
}

onMounted(() => {
  init()
})

onUnmounted(() => {
  // 移除消息处理器
  wsStore.unregisterMessageHandler(`chat_${userId.value}`)
})
</script>

<style scoped>
.chat-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  padding-bottom: 80px;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-service {
  justify-content: flex-end;
}

.message-user {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
  color: #969799;
}

.message-service .message-header {
  justify-content: flex-end;
}

.message-user .message-header {
  justify-content: flex-start;
}

.message-name {
  font-weight: 500;
}

.message-time {
  font-size: 11px;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 12px;
  word-wrap: break-word;
  line-height: 1.5;
  font-size: 14px;
}

.message-service .message-bubble {
  background-color: #1989fa;
  color: #fff;
  border-bottom-right-radius: 4px;
}

.message-user .message-bubble {
  background-color: #fff;
  color: #323233;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 8px 12px;
  padding-bottom: calc(8px + env(safe-area-inset-bottom));
  display: flex;
  align-items: flex-end;
  gap: 8px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  border-top: 1px solid #ebedf0;
}

.input-area :deep(.van-field) {
  flex: 1;
  background-color: #f7f8fa;
  border-radius: 8px;
  padding: 8px 12px;
}

.input-area :deep(.van-field__control) {
  font-size: 14px;
}

.input-area :deep(.van-button) {
  height: 36px;
  padding: 0 16px;
  border-radius: 8px;
}
</style>

